/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

const { reject } = require('lodash');
const { MyPromise } = require('./MyPromise');

function other() {
  return new MyPromise((resolve) => {
    resolve('other');
  })
}

const promise = new MyPromise((resolve, reject) => {
  // throw new Error('executor error');
  // resolve('成功');
  reject('失败');
  // setTimeout(() => {
  //   resolve('成功')
  // }, 2000)
})

// promise.then((val) => {
//   setTimeout(() => {
//     console.log('success111',val)
//   }, 2000)
//   return 'then链式调用111';
// }, (e) => {
//   setTimeout(() => {
//     console.log('fail111',e)
//   }, 2000)
// }).then((val) => {
//   console.log(val);
// })

// promise.then((val) => {
//   console.log('success222',val);
//   return other();
// }, (e) => {
//   console.log('fail222',e);
// }).then((val) => {
//   console.log(val);
// })

// const p1 = promise.then().then().then((val) => {
//   console.log('success333',val);
//   return other();
// }, (error) => {
//   console.log(error,'error1');
//   return 1000;
// })

// p1.then((value) => {
//   console.log(value, 'success444')
// }, (error) => {
//   console.log(error,'error2')
// })

const p2 = () => {
  return new MyPromise((resolve) => {
    setTimeout(() => {
      resolve('p2');
    }, 2000);
  })
}

const p3 = () => {
  return new MyPromise((resolve, reject) => {
    // resolve('p3');
    reject('error');
  })
}

// MyPromise.all(['1', '2', p2(), p3(), 'a']).then(result => {
//   console.log(result);
// })
// MyPromise.resolve('2').then(value => console.log(value));
// MyPromise.resolve(p2()).then(value => console.log(value));
// MyPromise.resolve(p3()).then(value => console.log(value));
// p3().finally(() => {
//   console.log('finally');
//   return p2();
// }).then(value => {
//   console.log(value)
// }, reason => {
//   console.log(reason)
// })

p3().then(value => console.log(value)).catch((error) => console.log(error));
